/*
 * SonarQube JavaScript Plugin
 * Copyright (C) 2011-2025 SonarSource Sàrl
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the Sonar Source-Available License for more details.
 *
 * You should have received a copy of the Sonar Source-Available License
 * along with this program; if not, see https://sonarsource.com/license/ssal/
 */
package org.sonar.plugins.javascript.bridge;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTesterJUnit5;

class AstProtoUtilsTest {

  @RegisterExtension
  public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.ERROR);

  @Test
  void should_parse_form_data_into_bridge_response() throws Exception {
    var node = AstProtoUtils.readProtobufFromBytes(getSerializedProtoData());
    assertThat(node).isNotNull();
    assertThat(node.getProgram().getBodyList().get(0).getExpressionStatement()).isNotNull();
  }

  @Test
  void should_log_error_if_ast_is_invalid() throws Exception {
    assertThat(AstProtoUtils.readProtobufFromBytes(new byte[] { 42 })).isNull();
    assertThat(logTester.logs(Level.ERROR)).containsExactly(
      "Failed to deserialize Protobuf message: While parsing a protocol message, the input ended unexpectedly in the middle of a field.  " +
        "This could mean either that the input has been truncated or that an embedded message misreported its own length."
    );
  }

  private static byte[] getSerializedProtoData() throws IOException {
    // the clear version of serialized.proto is `packages/jsts/tests/parsers/fixtures/ast/base.js`
    // it was generated by writing to a file the serialized data in the test `packages/jsts/tests/parsers/ast.test.ts`
    File file = new File("src/test/resources/files/serialized.proto");
    return Files.readAllBytes(file.toPath());
  }
}
